<?php

namespace App\Kuafu\User\Controller\Internal;

use App\Exceptions\BaseException;
use App\Exceptions\CustomValidateException;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\User\Enum\CodeEnum;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Exceptions\UserRoleException;
use App\Kuafu\User\Model\User;
use App\Kuafu\User\Model\UserRoleMapping;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserRoleService;
use App\Kuafu\User\Service\UserService;
use App\Kuafu\User\Service\WhiteIpService;
use App\Kuafu\User\Validate\UserValidate;
use App\Kuafu\User\Validate\UserValidateNew;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class UserController extends BaseController
{
    /*
     * 订货系统用
     * 根据门店ID获取可推送用户设备号以及手机号
     */
    public function getInfo(Request $request)
    {
        //门店ID Array
        //数据校验
        $valid = UserValidate::getShopIds($request);
        if ($valid) {
            return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }
        return $this->success(UserService::getPushRemind($request->post('shopIds')));
    }

    /**
     * 根据用户id列表查询用户信息
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserInfoByIds(Request $request): JsonResponse
    {
        $ids = $request->userIds ?? '';
        if (empty($ids)) {
            return $this->fail(CodeEnum::ERR_400000, CodeEnum::CODE_TEXT[CodeEnum::ERR_400000]);
        }
        $fields = $request->get('fields', ['*']);

        $userInfoByIds = UserService::getUserInfoByIds($ids, $fields);
        return $this->success($userInfoByIds);
    }

    /**
     * 根据用户id列表查询登录设备唯一ID
     * @param Request $request
     * @return JsonResponse
     */
    public function getRegistrationIdByIds(Request $request): JsonResponse
    {
        $ids = $request->get('userIds') ?? '';
        $ids = explode(',', $ids);
        if (empty($ids)) {
            return $this->fail(CodeEnum::ERR_400000, CodeEnum::CODE_TEXT[CodeEnum::ERR_400000]);
        }
        $userInfoByIds = UserService::getRegistrationIdByIds($ids);
        return $this->success($userInfoByIds);
    }


    /**
     * 通过昵称模糊查询用户信息
     */
    public function getWebUserList(Request $request)
    {
        $username = (string)$request->get("username", "");
        $webList  = UserService::getWebUserList($username);
        return $this->success($webList->toArray());
    }


    /**
     * 通过昵称模糊查询堪址处理人员
     */
    public function getSiteTaskHandlerList(Request $request): JsonResponse
    {
        $username            = (string)$request->get("username", "");
        $siteTaskHandlerList = UserService::getSiteTaskHandlerList($username);
        return $this->success($siteTaskHandlerList->toArray());
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws BaseException
     * @throws UserException
     * @throws UserRoleException
     */
    public function getAuthInfo(Request $request): JsonResponse
    {
        $userInfo = AuthService::getAuthUser();
        if ($userInfo->status == \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_STOP) {
            throw new BaseException(BaseCodeEnum::ERR_ACCOUNT_BANNED);
        }

        $userId         = AuthService::getUserId();
        $permissionList = AuthService::getUserAllWebPermission($userId, $this->brandId, $this->shopId);

        if (empty($permissionList)) {
            throw new BaseException(BaseCodeEnum::ERR_NO_ACCESS);
        }

        $userInfo['permissions'] = $permissionList;
//        $userInfo['whiteIps']    = (new WhiteIpService($userId, UserCodeEnum::WEB_TYPE))->getWhiteIps();

        return $this->success($userInfo->toArray());
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function decodeJwt(Request $request): JsonResponse
    {
        try {
            $jwtData = AuthService::decodeJwt();
            return $this->success($jwtData);
        } catch (\Exception $e) {
            return $this->fail(401, 'token无效');
        }
    }

    public function getUserPermission(Request $request)
    {
        $userId = $request->get('userId');

        $permissionList = AuthService::getUserAllWebPermission($userId, $this->brandId, $this->shopId);

        return $this->success(['lists' => $permissionList]);
    }

    /**
     * @throws UserException
     */
    public function getAuthUserInfo(Request $request)
    {
        $userId = $request->get('userId');

        $userInfo = User::query()->where('id', $userId)->first();

        if ($userInfo->status == \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_STOP) {
            throw new BaseException(BaseCodeEnum::ERR_ACCOUNT_BANNED);
        }

        $permissionList = AuthService::getUserAllWebPermission($userId, $this->brandId, $this->shopId);

        $userInfo['permissions'] = $permissionList;

        return $this->success($userInfo->toArray());
    }

    public function getUserInfoByMobiles(Request $request)
    {
        $mobiles = (string)$request->mobiles;
        if (!strlen($mobiles)) {
            return $this->fail(422, 'mobiles参数不能为空');
        }
        $mobiles = explode(',', (string)$request->mobiles);
        return $this->success(User::getUserInfoByMobiles($mobiles)->toArray());
    }


    /**
     * 创建用户
     * @param Request $request
     */
    public function create(Request $request)
    {
        $mobile   = $request->get('mobile', '');
        $name     = $request->get('name', '');
        $roles    = $request->get('roles', 0);
        $brandId  = (int)$request->header('brandId');
        $password = (string)$request->get('password', '');

        $valid = UserValidate::createInternal($request);
        if ($valid) {
            return $this->fail(UserCodeEnum::ERR_USER_NOT_INPUT, $valid);
        }

        [$userId, $password] = UserService::createOrRestore($this->brandId, $mobile, $name, $password);

        // roles是全量覆盖
        if ($roles) {
            UserRoleService::addUserRoleData($userId, $roles, $brandId);
        }

        return $this->success(['userId' => $userId, 'password' => $password]);
    }

    public function getShopOwnerCount(Request $request)
    {
        return $this->success(UserService::getShopOwnerCount());
    }

    public function setUserInfoById(Request $request)
    {
        $userId = $request->userId;
//        $feishuUserId = $request->feishuUserId;
        $field = $request->all();
        if (isset($field['userId'])) {
            unset($field['userId']);
        }
        UserService::setUserFieldByUserId($userId, $field);
        return $this->success();
    }

    // 通过username批量获取用户信息
    public function getInfoByUsernames(Request $request)
    {
        $usernames = $request->get('usernames');

        return $this->success(UserService::getInfoByUserames($usernames));
    }

    /**
     * 根据用户id列表查询用户信息
     * @param Request $request
     * @return JsonResponse
     */
    public function getRoleUserLists(Request $request): JsonResponse
    {
        $roleId = $request->roleId ?? 0;
        if (empty($roleId)) {
            return $this->fail(BaseCodeEnum::ERR_400000, BaseCodeEnum::CODE_TEXT[BaseCodeEnum::ERR_400000]);
        }
        return $this->success(UserRoleService::roleUserLists($roleId));
    }

    /**
     * 员工档案缺失门店,员工 列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getProblemShopStaffList(Request $request): JsonResponse
    {
        return $this->success(UserService::getProblemShopStaffList());
    }


    /**
     * 获取店长列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopManagerUserLists(Request $request): JsonResponse
    {
        $roleId = config('merchant.manager_role_id');
        return $this->success(UserRoleService::roleUserLists($roleId));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopManagerUserByShopId(Request $request): JsonResponse
    {
        $roleId        = config('merchant.manager_role_id');
        $shopIds       = $request->get('shopIds', []);
        $shopCodes     = $request->get('shopCodes', []);
        $filterWebUser = (int)$request->get('filterWebUser', 0);

        if ($shopCodes) {
            $shopIds = Shop::query()->whereIn('shopCode', $shopCodes)->pluck('id')->toArray();
        }

        return $this->success(UserRoleService::getShopManageList($roleId, $shopIds, $filterWebUser));
    }

    /**
     * 查询用户作为店长关联的所有店铺id
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopIdsByUserManager(Request $request): JsonResponse
    {
        $userId = $request->get('userId');
        $roleId = config('merchant.manager_role_id');

        return $this->success(['shopIds' => UserRoleService::getShopIdsByUserManager($userId, $roleId)]);
    }

    /**
     * 根据条件获取通知的人 带分页
     * @param Request $request
     * @return JsonResponse
     */
    public function getNotifyAllUserLists(Request $request): JsonResponse
    {
        $lastId   = $request->get('lastId', 0);
        $type     = $request->get('type', 0);
        $cityCode = $request->get('cityCode', 'ALL');
        return $this->success(UserService::getNotifyAllUserLists($lastId, $type, $cityCode));
    }

    /**
     * 判断用户是否是该职位
     * @param Request $request
     * @return JsonResponse
     */
    public function isRoleUser(Request $request): JsonResponse
    {
        $roleId = $request->roleId ?? 0;
        $userId = $request->userId ?? 0;
        if (empty($roleId) || empty($userId)) {
            return $this->fail(BaseCodeEnum::ERR_400000, BaseCodeEnum::CODE_TEXT[BaseCodeEnum::ERR_400000]);
        }
        return $this->success(UserRoleService::isRoleUser($roleId, $userId));
    }

    /**
     * 职位配置输出
     * @return JsonResponse
     */
    public function roleIdsConfig()
    {
        return $this->success(['role' => config('merchant')]);
    }

    /**
     * 获取用户角色
     * @param Request $request
     * @return JsonResponse
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function role(Request $request): JsonResponse
    {
        $requestParams = UserValidateNew::userRoleValidate($request->all());
        return $this->success(UserService::userRole($requestParams));
    }

    /**
     * 获取飞书用户信息
     *
     * @param Request $request
     * @return JsonResponse
     * @throws BaseException
     * @throws ContainerExceptionInterface
     * @throws CustomValidateException
     * @throws NotFoundExceptionInterface
     */
    public function getFsUserByUserIds(Request $request): JsonResponse
    {
        $requestParams = UserValidateNew::fsUserByUserIdsValidate($request->all());
        return $this->success(UserService::getFsUserByUserIds($requestParams));
    }


    /**
     * 根据权限获得对应的用户列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserListByPower(Request $request): JsonResponse
    {
        $roles = $request->get('roles', '');
        return $this->success(UserService::getUserListByPower($roles));
    }

    /**
     * 通过职位模糊查询用户列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getUsersByRoleName(Request $request): JsonResponse
    {
        $roleName = (string)$request->get('roleName');
        $type     = (int)$request->get('type', 1);
        $shopId   = (int)$request->get('shopId', 0);
        $isKf     = $request->get('isKf', 1);

        return $this->success(UserService::getUsersByRoleName($roleName, $type, $shopId, $isKf));
    }

    /**
     * 获得在省份内未开通的店长
     * @param Request $request
     * @return JsonResponse
     */
    public function getNoPowerWalletByProvince(Request $request): JsonResponse
    {
        $provinceCode = (int)$request->get('provinceCode', 310000);
        return $this->success(UserService::getNoPowerWalletByProvince($provinceCode));
    }

    /**
     * 密码登录
     * @param Request $request
     * @return JsonResponse
     */
    public function loginByPassword(Request $request): JsonResponse
    {
        $this->validate($request, [
            'mobile'   => 'required|string',
            'password' => 'required|string',
            'formIp'   => 'required|string',
        ]);

        $request->merge(['username' => $request->mobile]);

        $jwt = AuthService::login($request, UserCodeEnum::WEB_TYPE, $request->isLasting, '', '', '', $request->formIp);

        $userInfo = AuthService::getAuthUser();

        return $this->success([
            'jwt'      => $jwt,
            'userInfo' => $userInfo->only(['id', 'username', 'mobile']),
        ]);
    }

    /**
     * 获得商家APP登录的JWT
     * @param Request $request
     * @return JsonResponse
     */
    public function getMerchantLoginJwt(Request $request): JsonResponse
    {
        $userIp = (string)$request->post('userIp', '');
        $userId = (int)$request->post('userId', 0);

        if ($userId && $userIp) {
            return $this->success(UserService::getMerchantLoginJwt($userId, $userIp));
        } else {
            return $this->fail(400, '参数错误');
        }
    }

    /**
     * 模糊查询用户名称
     * @param Request $request
     * @return JsonResponse
     */
    public function getRmsUserIdByUserName(Request $request): JsonResponse
    {
        $userName = (string)$request->get('userName', '');

        return $this->success(UserService::getRmsUserIdByUserName($userName));
    }

    /**
     * 门店内的用户列表
     * @param Request $request
     * @return JsonResponse
     */
    public function usersInShop(Request $request): JsonResponse
    {
        $shopId = $request->get('shopId');

        $this->validate($request, [
            'shopId' => 'required|integer',
        ]);

        $users = UserService::usersInShop($shopId);

        return $this->success($users);
    }


    /**
     * 门店内的用户列表
     * @param Request $request
     * @return JsonResponse
     */
    public function usersInShops(Request $request): JsonResponse
    {
        $shopId = $request->get('shopIds');

        $this->validate($request, [
            'shopIds' => 'required|array',
        ]);

        $users = UserService::usersInShops($shopId);

        return $this->success($users);
    }

    /**
     * 添加导入的员工信息
     * @param Request $request
     * @return JsonResponse
     */
    public function importSupplierCruiseStaff(Request $request): JsonResponse
    {
        $userList = (array)$request->post('userList', []);
        $data     = UserService::importSupplierCruiseStaff($userList);
        return $this->success($data);
    }
}
